package cn.nexd.app.collector.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;

import app.xu.com.listtext.listener.OnTextItemClickListener;
import app.xu.com.listtext.view.ListTextView;
import cn.nexd.app.collector.R;
import cn.nexd.app.collector.model.FloorLayer;
import cn.nexd.app.collector.overly.MoveLocationPositionOverlay;
import cn.nexd.app.collector.presenter.map.NexdMapContract;
import cn.nexd.app.collector.presenter.map.NexdMapPresenter;
import cn.nexd.app.collector.util.ProgressUtil;
import cn.nexd.app.collector.util.UMengUtil;
import cn.nexd.map.rendering.SVGMapViewListener;
import cn.nexd.map.rendering.core.componet.SVGMapView;
import cn.nexd.map.rendering.overlay.SVGMapLocationOverlay;
import cn.nexd.sdk.location.NexdIndoorLocationResult;
import cn.nexd.utils.framework.error.NexdCrashException;
import cn.nexd.utils.framework.tools.Logger;

public class NexdMapActivity extends AppCompatActivity implements NexdMapContract.View, SVGMapViewListener, OnTextItemClickListener {

    private static final String TAG = "NexdMapActivity";

    private static final int LOCATION_OVERLAY = 1;

    private SVGMapView mapView;
    private NexdMapContract.Presenter presenter;

    private SVGMapLocationOverlay locationOverlay;

    private MoveLocationPositionOverlay moveLocationPositionOverlay;
    private ListTextView listTextView;
    private ArrayList<FloorLayer> floors;
    private boolean autoChange;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nexd_map);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        mapView = (SVGMapView) findViewById(R.id.nexdMap);
        listTextView = (ListTextView) findViewById(R.id.ltv_navigate);


        Intent intent = getIntent();
        long buildingId = Long.parseLong(intent.getStringExtra("buildingId"));
        int interval = Integer.parseInt(intent.getStringExtra("interval"));
        int buffer = Integer.parseInt(intent.getStringExtra("buffer"));
        String model = intent.getStringExtra("model");
        autoChange = intent.getBooleanExtra("autoChange", false);
        floors = intent.getParcelableArrayListExtra("floors");
        String buildingName = intent.getStringExtra("buildingName");

        presenter = new NexdMapPresenter(this, this);
        toolbar.setTitle(buildingName);

        setListTextView(floors);


        if (buildingId == 0) {
            showToast("参数异常，无法找到地图文件，请检查配置！");
            return;
        }

        presenter.initLocation(model, interval, buildingId, buffer);
        presenter.loadMap(floors.get(0).getFloorId());
        listTextView.setItemSelectedColor(R.color.text_environment_wifi);
        listTextView.setOnTextItemClickListener(this);
    }

    @Override
    public void loadMap(String path) {
        try {
            ProgressUtil.show(this, "", "载入中...", false);
            mapView.registerMapViewListener(this);
            mapView.loadMap(new FileInputStream(path));
        } catch (FileNotFoundException e) {
            NexdCrashException.getInstance().reportException(e);
            UMengUtil.getInstance().reportError(this, e);
            e.printStackTrace();
            showToast("参数异常，无法找到地图文件，请检查配置!");
        }
    }


    private void setListTextView(ArrayList<FloorLayer> floorLayers) {
        listTextView.setItems(presenter.initSelectItems(floorLayers));
    }

    @Override
    public void updateLocationPoint(NexdIndoorLocationResult nexdIndoorLocationResult) {
//
//        if (moveLocationPositionOverlay == null) {
//            moveLocationPositionOverlay = new MoveLocationPositionOverlay(mapView);
//            mapView.addOverlay(moveLocationPositionOverlay, LOCATION_OVERLAY);
//        }
//
//        Logger.debug(TAG, "updateLocationPoint: 更新定位点数据");
//        moveLocationPositionOverlay.setPosition(new PointF(nexdIndoorLocationResult.getIndoorPositionX(), nexdIndoorLocationResult.getIndoorPositionY()));
        if (locationOverlay == null) {
            locationOverlay = new SVGMapLocationOverlay(mapView);
            mapView.addOverlay(locationOverlay, LOCATION_OVERLAY);
        }
        Logger.debug(TAG, "updateLocationPoint: 更新等位点信息");
        locationOverlay.setPosition(new PointF(nexdIndoorLocationResult.getIndoorPositionX(), nexdIndoorLocationResult.getIndoorPositionY()));
        mapView.refresh();
    }

    @Override
    public void changeFloor(String path, int witch) {
        try {
            ProgressUtil.show(this, "", "切换中...", false);
            mapView.removeAllOverlay();
            locationOverlay = null;
//            moveLocationPositionOverlay = null;
            mapView.setCurrentFloor(new FileInputStream(path), this);
            listTextView.setSelection(witch);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            UMengUtil.getInstance().reportError(this, e);
            NexdCrashException.getInstance().reportException(e);
            showToast("地图加载失败");
        }
    }

    @Override
    public void notifyChangeFloor(final String floorName, final long floorId, final int witch) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("定位到您在" + floorName + "层，是否切换？")
                .setTitle("提醒")
                .setCancelable(false)
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Logger.debug(TAG, "onClick: 切换楼层 floorName = " + floorName + "\n floorId = " + floorId + "\n index = " + witch);
                        presenter.changeFloor(floorId);
                        listTextView.setSelection(witch);
                    }
                }).show();
    }

    @Override
    public void initView() {

    }

    @Override
    public void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(NexdMapActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void startActivity() {

    }

    @Override
    public void printLog(String msg) {

    }

    @Override
    public void onMapLoadComplete(long floorId, String mallName) {
        Logger.debug(TAG, "地图加载完成  " + floorId + "    " + mallName);
        ProgressUtil.dismiss();
        presenter.startLocation(autoChange);
    }

    @Override
    public void onMapLoadError() {
        showToast("地图文件异常， 加载失败！");
    }

    @Override
    public void onGetCurrentMap(Bitmap bitmap) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        UMengUtil.getInstance().onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        UMengUtil.getInstance().onPause(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                this.finish();
        }
        return false;
    }

//    @Override
//    public void onBackPressed() {
//        super.onBackPressed();
//        this.finish();
//    }

    @Override
    protected void onStop() {
        super.onStop();
        presenter.stopLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.destroyLocation();
    }

    @Override
    public void onItemClickListener(int witch, String text) {

        Logger.debug(TAG, "onItemClickListener:  floorId = " + floors.get(witch).getFloorId());
        presenter.changeFloor(floors.get(witch).getFloorId());
    }
}
